package com.baaio.conn;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;
import com.baaio.conn.Interface.GetDataIterface;
import com.baaio.reflect.BaaioReflect;
import com.baaio.util.GetInfo;

/**
 * 
 * 扩展类 该类用于查询整个表的信息，并把结果用hashmap 储存。key为字段名字。value为值。
 * <p>
 * 每一个map为一条信息 最后把查询的map保存在list里。
 * 
 * 
 */
public class GetAllListData implements GetDataIterface
{

	private String sqlORmysql;
	private String sql2;
	private String dbaName;
	private BaaioConnImpl bci;

	public GetAllListData()
	{

		setsqlORmysql(GetInfo.getInstance().getSqlORmysql());
		setDbaName(GetInfo.getInstance().getDb());
		bci = new BaaioConnImpl();
	}

	public GetAllListData(String DBName)
	{

		setsqlORmysql(GetInfo.getInstance().getSqlORmysql());
		setDbaName(DBName);
		bci = new BaaioConnImpl(getDbaName());
	}

	/**
	 * 获取指定字段的数据。f如果为true就是去掉重复项。
	 * 
	 * @param tb
	 *            表名字
	 * @param itemName
	 *            字段名字
	 * @param f
	 * @return ArrayList<String>
	 */
	public ArrayList<String> getSingleData(String tb, String itemName, boolean f)
	{

		ArrayList<HashMap<String, String>> list = getSelect(tb, "", "");
		ArrayList<String> list2 = new ArrayList<String>();
		HashSet<String> set = new HashSet<String>();
		for (HashMap<String, String> map : list)
		{
			if (f)
			{
				set.add(map.get(itemName));
			}
			else
			{
				list2.add(map.get(itemName));
			}
		}

		if (f)
		{
			for (Iterator<String> i = set.iterator(); i.hasNext();)
			{
				list2.add(i.next());
			}
		}

		for (int i = 0; i < list2.size() - 1; i++)
		{

			for (int j = 1; j < list2.size() - i; j++)
			{
				String a;
				if ((list2.get(j - 1)).compareTo(list2.get(j)) > 0)
				{ // 比较两个整数的大小

					a = list2.get(j - 1);
					list2.set((j - 1), list2.get(j));
					list2.set(j, a);
				}
			}
		}
		return list2;
	}

	/**
	 * 该方法与getSingleData 一样就是返回的类型不一样。
	 * 
	 * @param tb
	 * @param itemName
	 * @param f
	 * @return Vector<String>
	 */
	public Vector<String> getSingleDataVector(String tb, String itemName,
			boolean f)
	{

		ArrayList<String> list = getSingleData(tb, itemName, f);
		Vector<String> vector = new Vector<String>();
		for (Iterator<String> i = list.iterator(); i.hasNext();)
		{
			vector.add(i.next());
		}

		return vector;
	}

	/**
	 * 该方法的用处在于查询在指定字段名下指定值得结果。<br>
	 * 
	 * @param tb
	 *            查询表名
	 * @param idName
	 *            字段名 为空""查询所有字段
	 * @param idValue
	 *            字段值 在字段为空的情况下该值也为空！
	 * @return 返回ArrayList
	 */
	public ArrayList<HashMap<String, String>> getSelect(String tb,
			String idName, String idValue)
	{

		ArrayList<String> list3 = new ArrayList<String>();
		String condition = null;
		if (null != tb || "" != tb)
		{

			if ("".equals(idValue) || "".equals(idName) || null == idName)
			{
				condition = "";
				if ("".equals(idName))
				{
					list3.add("*");
				}
				else
				{
					list3.add(idName);
				}
			}
			else
			{
				list3.add("*");
				condition = " where " + idName + " like '%" + idValue + "%'";
			}
		}

		return handel(tb, list3, condition);

	}

	public ArrayList<HashMap<String, String>> handel(String tb,
			ArrayList<String> itemName, String condition)
	{

		ResultSet rs = null;
		rs = bci.queryData(tb, itemName, condition);
		try
		{

			ArrayList<String> tableName = getColumnName(tb);// 获得需要查询tb表字段名字！

			ArrayList<HashMap<String, String>> list2 = new ArrayList<HashMap<String, String>>();
			int xh = 1;
			int i = 1;
			// ========================遍历结果集。并把值装入map
			while (rs.next())
			{
				HashMap<String, String> map = new HashMap<String, String>();
				for (String tn : tableName)
				{
					if (null == tn || "" == tn)
					{
						break;
					}
					else if (tn == "xh")
					{
						map.put(tn, Integer.toString(xh++));
					}
					else
					{
						map.put(tn, rs.getString(i++));
					}
				}
				list2.add(map);
				i = 1;
			}
			return list2;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public ArrayList<HashMap<String, String>> getSelect(String tb,
			ArrayList<String> itemName, String condition)
	{

		return handel(tb, itemName, condition);
	}

	@Override
	public ArrayList<HashMap<String, String>> getSelect(Object object)
	{

		return getSelect(new BaaioReflect().getTableName(object), "", "");
	}

	/**
	 * 获得tb表的所有表单的名字
	 * 
	 * @param tb
	 *            表名
	 * @return ArrayList
	 * @throws Exception
	 */
	public ArrayList<String> getColumnName(String tb) throws Exception
	{

		if (sqlORmysql.equals("mysql"))
		{
			setSql2("SELECT  COLUMN_NAME FROM  `information_schema`.`COLUMNS`  where `TABLE_SCHEMA`='"
					+ getDbaName() + "'  and  `TABLE_NAME`='" + tb + "'");
		}
		else if (sqlORmysql.equals("sql") || sqlORmysql.equals("oldsql"))
		{
			setSql2("Select Name from syscolumns where ID=OBJECT_ID(N'" + tb
					+ "') Order By ColID");
		}
		ArrayList<String> tableName = new ArrayList<String>();// 获得需要查询tb表字段名字！
		ResultSet rst = bci.query(getSql2());
		while (rst.next())
		{
			tableName.add(rst.getString(1));
		}
		rst.close();
		tableName.add("xh");
		return tableName;
	}

	public Vector<String> getColumnManeVector(String tb) throws Exception
	{

		ArrayList<String> list = getColumnName(tb);
		Vector<String> vector = new Vector<String>();

		for (Iterator<String> i = list.iterator(); i.hasNext();)
		{
			vector.add(i.next());
		}
		return vector;
	}

	public Object[] getColumnNameObject(String tb) throws Exception
	{

		ArrayList<String> list = getColumnName(tb);
		Object[] object = new Object[list.size() - 1];
		for (int k = 0; k < list.size() - 1; k++)
		{
			object[k] = list.get(k);
		}
		return object;
	}

	/**
	 * 该方法用于获得类JTable(Object[][] rowData, Object[] columnNames) rowData数据。<br>
	 * 
	 * 使用方法：比如要获得表A中的两个字段name,sex；所有的值，并返回为Object数组<br>
	 * 
	 * GetAllListData gd = new GetAllListData();<br>
	 * ArrayList<String> items = new ArrayList<String>();<br>
	 * items.add("name");<br>
	 * items.add("sex");<br>
	 * Object[][] data = gd.getTableData("A",items);<br>
	 * 
	 * 那么data就是需要的二维数组<br>
	 * 
	 * @param tbName
	 *            需要查询目标表的名字
	 * @param items
	 *            需要获得指定字段的值
	 * @return Object[][]
	 */
	public Object[][] getTableData(String tbName, ArrayList<String> items)
	{

		if (items.isEmpty() || items == null || items.equals(null))
		{
			try
			{
				items = new GetAllListData().getColumnName(tbName);
			}
			catch (Exception e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		ArrayList<HashMap<String, String>> list = getSelect(tbName, "", "");
		ArrayList<String[]> list2 = new ArrayList<String[]>();
		String[] str = new String[items.size()];
		for (HashMap<String, String> map : list)
		{

			for (int i = 0; i < items.size(); i++)
			{
				str[i] = map.get(items.get(i));
			}
			list2.add(str);
			str = new String[items.size()];
		}

		Object[][] object = new Object[list2.size()][];
		for (int k = 0; k < list2.size(); k++)
		{
			object[k] = list2.get(k);
		}
		return object;
	}

	public Object[][] getTableData(String tbName)
	{

		return getTableData(tbName, new ArrayList<String>());
	}

	private String getDbaName()
	{

		return dbaName;
	}

	private void setDbaName(String dbaName)
	{

		this.dbaName = dbaName;
	}

	private void setsqlORmysql(String sqlORmysql)
	{

		this.sqlORmysql = sqlORmysql;
	}

	private String getSql2()
	{

		return sql2;
	}

	private void setSql2(String sql2)
	{

		this.sql2 = sql2;
	}

	/**
	 * 如果要查询另外的数据，可以调用这个方法。但是每次调用提前数据库之前都的提前调用设置数据库名字。 该方法添加一次数据名，只会查询一次。
	 * 
	 * @param DBName
	 */

	public void close()
	{

		bci.close();
	}

	@Override
	public ArrayList<HashMap<String, String>> getSelect(Object object,
			String value)
	{

		BaaioReflect brf = new BaaioReflect();
		String key = brf.getValue(object).get("key");
		String tableName = brf.getTableName(object);
		return getSelect(tableName, key, value);
	}

	@Override
	public Vector<String> getSelectOneRow(String tableName, String item,
			String value)
	{

		ResultSet rs = bci.queryData(tableName, item, value);
		Vector<String> vector = new Vector<String>();

		try
		{
			ArrayList<String> list = getColumnName(tableName);
			while (rs.next())
			{
				for (String str : list)
				{
					if(str != "xh")
					vector.add(rs.getString(str));
				}
			}
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return vector;
	}

	@Override
	public ArrayList<Vector<String>> getSelectListVector(String tableName,
			String item, String value) {
		ResultSet rs = bci.queryData(tableName, item, value);
		
		ArrayList<Vector<String>> list = new ArrayList<Vector<String>>();
		
		try
		{
			ArrayList<String> list2 = getColumnName(tableName);
			while (rs.next())
			{
				Vector<String> vector = new Vector<String>();
				for (String str : list2)
				{
					if(str != "xh")
					vector.add(rs.getString(str));
				}
				list.add(vector);
			}
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return list;
	}
	
	

}
